package bom.example.common.jsonfilter;


import com.alibaba.fastjson.JSONObject;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Arrays;
import java.util.HashSet;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/12 13:55
 * @since JDK 1.8
 */
@ControllerAdvice
public class ResultResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        // TODO Auto-generated method stub
        JsonFilterObject jsonFilterObject = new JsonFilterObject();
        if (returnType.getMethod()!=null&&returnType.getMethod().isAnnotationPresent(SerializeField.class)) {
            Object obj = returnType.getMethod().getAnnotation(SerializeField.class);
            handleAnnotation(SerializeField.class, obj, jsonFilterObject);
            if (body instanceof JSONObject){
                jsonFilterObject.setJsonObject(body);
            }else {
                jsonFilterObject.setJsonObject(body);
            }
            return jsonFilterObject;
        } else {
            return body;
        }

    }



    private void handleAnnotation(Class<SerializeField> clazz, Object object, JsonFilterObject jsonFilterObject) {
        String[] includes = {};
        String[] excludes = {};
        Class<SerializeField> objClass = null;
        if (clazz.equals(SerializeField.class)) {
            SerializeField serializeField = (SerializeField) object;
            /**
             * 获取注解使用处的参数信息，如@SerializeField(clazz = Address.class,includes = {"school", "home", "user"})
             * 获取clazz及includes等信息
             */
            includes = serializeField.includes();
            excludes = serializeField.excludes();
            objClass = serializeField.clazz();
        }
        if (includes.length > 0 && excludes.length > 0) {
            //throw new IncludesAndExcludesConflictException("Can not use both includes and excludes in the same annotation!");
        } else if (includes.length > 0) {
            jsonFilterObject.getIncludes().put(objClass, new HashSet<>(Arrays.asList(includes)));
        } else if (excludes.length > 0) {
            jsonFilterObject.getExcludes().put(objClass, new HashSet<String>(Arrays.asList(excludes)));
        }
    }


}
